package com.ruoyi.data.service.impl;

import cn.dev33.satoken.temp.SaTempUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.data.domain.bo.SysUserTokenBo;
import com.ruoyi.data.domain.vo.SysUserTokenVo;
import com.ruoyi.data.domain.SysUserToken;
import com.ruoyi.data.mapper.SysUserTokenMapper;
import com.ruoyi.data.service.ISysUserTokenService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用户tokenService业务层处理
 *
 * @author lcx
 * @date 2023-11-29
 */
@RequiredArgsConstructor
@Service
public class SysUserTokenServiceImpl implements ISysUserTokenService {

    private final SysUserTokenMapper baseMapper;
    private final SysUserMapper sysUserMapper;

    /**
     * 查询用户token
     */
    @Override
    public SysUserTokenVo queryById(Long userId){
        return baseMapper.selectVoById(userId);
    }

    /**
     * 查询用户token列表
     */
    @Override
    public TableDataInfo<SysUserTokenVo> queryPageList(SysUserTokenBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserToken> lqw = buildQueryWrapper(bo);
        Page<SysUserTokenVo> result = baseMapper.sysUserTokenPageList(pageQuery.build(), lqw);
        assemblyData(result.getRecords());
        return TableDataInfo.build(result);
    }


    /**
     * 组装数据
     * @param vos
     */
    private void assemblyData(List<SysUserTokenVo> vos){
        vos.forEach(p-> {
            SysUser sysUser = sysUserMapper.selectById(p.getUserId());
            if (ObjectUtil.isNotNull(sysUser)){
                p.setUserName(sysUser.getUserName());
            }


            DateTime dateTime = DateUtil.offsetDay(p.getCreateTime(),
                Math.toIntExact(
                    p.getExpirationTime() == 0 ? 365 * 100 : p.getExpirationTime()
                ));
            p.setExpirationDate(dateTime);
        });
    }

    /**
     * 查询用户token列表
     */
    @Override
    public List<SysUserTokenVo> queryList(SysUserTokenBo bo) {
        LambdaQueryWrapper<SysUserToken> lqw = buildQueryWrapper(bo);

        List<SysUserTokenVo> sysUserTokenVos = baseMapper.selectVoList(lqw);
        assemblyData(sysUserTokenVos);
        return sysUserTokenVos;
    }

    private LambdaQueryWrapper<SysUserToken> buildQueryWrapper(SysUserTokenBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserToken> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getExpirationTime() != null, SysUserToken::getExpirationTime, bo.getExpirationTime());
        lqw.eq(bo.getUserId()!=null, SysUserToken::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotEmpty(bo.getDelFlag()), SysUserToken::getDelFlag, bo.getDelFlag());

        lqw.orderByAsc(SysUserToken::getDelFlag).orderByAsc(SysUserToken::getUserId).orderByDesc(SysUserToken::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户token
     */
    @Override
    @Transactional
    public Boolean insertByBo(SysUserTokenBo bo) {
        SysUserToken add = BeanUtil.toBean(bo, SysUserToken.class);
        validEntityBeforeSave(add);

        String token = IdUtil.simpleUUID();


        add.setUserId(LoginHelper.getUserId());
        add.setToken(token);

        LambdaQueryWrapper<SysUserToken> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserToken::getUserId, LoginHelper.getUserId());

        List<SysUserToken> sysUserTokens = baseMapper.selectList(queryWrapper);

        List<Long> delList = sysUserTokens.stream().map(SysUserToken::getUserId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(delList)){
            baseMapper.deleteBatchIds(delList);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());

            SysUser user = new SysUser();
            user.setUserId(LoginHelper.getUserId());
            user.setToken(token);

            sysUserMapper.updateById(user);

            //失效之前的token
            sysUserTokens.stream().forEach(s -> {
                CacheUtils.evict(CacheNames.DATA_TOKEN_USER, s.getToken());
            });
        }
        return flag;
    }

    /**
     * 修改用户token
     */
    @Override
    public Boolean updateByBo(SysUserTokenBo bo) {
        SysUserToken update = BeanUtil.toBean(bo, SysUserToken.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserToken entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户token
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<SysUserTokenVo> sysUserTokenVos = baseMapper.selectVoBatchIds(ids);

        boolean b = baseMapper.deleteBatchIds(ids) > 0;

        sysUserTokenVos.stream().forEach(s -> {
            CacheUtils.evict(CacheNames.DATA_TOKEN_USER, s.getToken());
        });
        return b;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String generateToken(SysUser user) {

        SysUser sysUser = sysUserMapper.selectById(user.getUserId());
        if (ObjectUtil.isNull(sysUser)){
            throw new RuntimeException("用户不存在！");
        }
        //失效其他token
        baseMapper.deleteById(sysUser.getUserId());

        SysUserToken add = new SysUserToken();
        add.setUserId(sysUser.getUserId());
        add.setToken(IdUtil.simpleUUID());
        add.setExpirationTime(user.getExpirationTime());
        boolean flag = baseMapper.insert(add) > 0;
        //清除缓存
        if (flag){
            CacheUtils.evict(CacheNames.DATA_TOKEN_USER, sysUser.getToken());
        }
        return add.getToken();
    }

    @Override
    public Date getTokenExpirationTime(String token) {
        SysUserToken sysUserToken = baseMapper.selectOne(new LambdaQueryWrapper<SysUserToken>()
            .eq(SysUserToken::getToken, token)
            .eq(SysUserToken::getDelFlag, "0")
        );

        if (ObjectUtil.isNull(sysUserToken)){
            return null;
        }

        //如果是0 给100年有效期
        return DateUtil.offsetDay(sysUserToken.getCreateTime(),
            Math.toIntExact(
                sysUserToken.getExpirationTime() == 0 ? 365 * 100 : sysUserToken.getExpirationTime()
            ));
    }
}
